﻿// Open Source: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Project: YoProgramo.NET (http://code.google.com/p/yoprogramo/)
// Autor: Fabian Figueredo (info@fabianfigueredo.com.ar)
// Blog: blog.yoprogramo.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Validator.Engine;
using YoProgramo.Domain.Core.Interfaces;
using YoProgramo.Infrastructure.Tools.NHValidator;

namespace YoProgramo.Domain.BusinessLogic.Service
{
    public class VisitService<Ttentity> : IVisitService<Ttentity> {

        public VisitService(IVisitRepository<Ttentity> visitRepository, IUserRepository userRepository)
        {
            VisitRepository = visitRepository;
            UserRepository = userRepository;
        }

        public IVisitRepository<Ttentity> VisitRepository { get; set; }
        public IUserRepository UserRepository { get; set; }


        #region IVisitService<Ttentity> Members

        public IList<IVisit<Ttentity>> GetAll() {
            return (IList<IVisit<Ttentity>>)VisitRepository.GetAll();
        }

        public IList<IVisit<Ttentity>> GetAllBy(Ttentity obj) {
            return (from s in GetAll()
                    where ((IEntityCommon)s.VisitFor).Id == ((IEntityCommon)obj).Id
                    orderby s.DateVisit descending
                    select s).ToList();
        }

        public NHibernate.Validator.Engine.InvalidValue[] Create(IVisit<Ttentity> obj) {
            InvalidValue[] validatorErrors = new NHValidatorWrapper<IVisit<Ttentity>>().Validate(obj);

            if (validatorErrors.Count() < 1)
                VisitRepository.SaveOrUpdate(obj);

            return validatorErrors;
        }

        public bool Update(IVisit<Ttentity> obj) {
            try {
                VisitRepository.SaveOrUpdate(obj);
                return true;
            } catch {
                return false;
            }
        }

        public void Delete(IVisit<Ttentity> obj) {
            VisitRepository.Delete(obj);
        }

        #endregion
    }
}